/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="history-task">
        <div class="table-data">
            <sf-grid>
                <sf-toolbar ref="toolbar">
                    <div>
                        <span
                            style="display: inline-block;font-size: 14px;margin-right: 16px;">执行方式</span>
                        <el-select v-model="searchParams.scheduleMode"
                                   size="small"
                                   placeholder="请选择">
                            <el-option value="" :label=" _('全部') "></el-option>
                            <el-option
                                v-for="item in scheduleModeOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div>
                        <span
                            style="display: inline-block;font-size: 14px;margin-right: 16px;margin-left: 24px;">日期</span>
                        <el-date-picker
                            v-model="dateList"
                            type="daterange"
                            range-separator="至"
                            size="small"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd"
                            @change="_datePickerChange">
                        </el-date-picker>
                    </div>
                    <div>
                        <span
                            style="display: inline-block;font-size: 14px;margin-right: 16px;margin-left: 24px;">状态</span>
                        <el-select v-model="searchParams.jobStatus"
                                   size="small"
                                   placeholder="请选择">
                            <el-option value="" :label=" _('全部') "></el-option>
                            <el-option
                                v-for="item in jobStatusOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div style="display: inline-flex;">
                        <sf-button-primary
                            style="width: 88px; color: #FFFFFF; margin: 0 8px 0 24px"
                            @click="_startSearch">{{ _('筛选') }}
                        </sf-button-primary>
                        <sf-button
                            style="width: 88px; border: 1px solid #c5cedb;"
                            @click="_reset"> {{ _('重置') }}
                        </sf-button>
                    </div>
                    <sf-searchfield
                        v-model="searchParams.search"
                        class="pull-right"
                        placeholder="搜索"
                        :default-width="220"
                        @trigger="_startSearch"
                        @clear="_startSearch"/>
                </sf-toolbar>
                <sf-table
                    ref="table"
                    :options="options_fix"
                    @sort="onSort"
                    @pagechange="_onPageChange"
                    @sizechange="_onSizeChange">
                    <sf-table-column
                        data-index="jobName"
                        :title="_('任务名称')"
                        :default-width="100">
                        <lang>任务名称</lang>
                    </sf-table-column>
                    <template slot="jobName"
                              slot-scope="{value, record}">
                        <el-link :underline="false" type="primary" @click="toDetail(record)">{{ value }}</el-link>
                    </template>
                    <sf-table-column
                        data-index="jobStatus"
                        :default-width="100">
                        <lang>状态</lang>
                    </sf-table-column>
                    <template slot="jobStatus"
                              slot-scope="{value,record}">
                        <span :class="['table-status__'+value,'table-status__point']">{{ HISTORY_STATUS_MAP[value]
                            }}</span>
                        <span v-if="value==='queue'">( {{ record.jobInQueue }} )</span>
                    </template>
                    <sf-table-column
                        data-index="scheduleMode"
                        :default-width="100">
                        <lang>执行方式</lang>
                    </sf-table-column>
                    <template slot="scheduleMode"
                              slot-scope="{value}">
                        {{ SCHEDULE_MAP[value] }}
                    </template>
                    <sf-table-column
                        data-index="startTime"
                        :sort-able="true"
                        :default-width="100">
                        <lang>开始时间</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="endTime"
                        :sort-able="true"
                        :default-width="100">
                        <lang>结束时间</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="executeTime"
                        :sort-able="true"
                        :default-width="100">
                        <lang>运行时长</lang>
                    </sf-table-column>
                    <template slot="executeTime"
                              slot-scope="{value}">
                        {{ value | secToTime }}
                    </template>
                    <sf-table-column
                        data-index="outputDataset"
                        :default-width="100">
                        <lang>输出数据集</lang>
                    </sf-table-column>
                    <template slot="outputDataset"
                              slot-scope="{value, record}">
                        <span class="output">
                        <span :title="`${record.outputDataspace}/${value}`"
                              class="output__text ellipsis">{{ record.outputDataspace }}/{{ value }}</span>
                            <i v-clipboard:copy="`${record.outputDataspace}/${value}`"
                               v-clipboard:success="copySuccess"
                               :title=" _('复制') "
                               class="iconfont iconsip-copy"></i>
                        </span>
                    </template>
                    <sf-table-column data-index="opr"
                                     :default-width="70">
                        <lang>操作</lang>
                    </sf-table-column>
                    <!--额外操作-->
                    <template slot="opr"
                              slot-scope="{record}">
                        <div class="table-opr">
                            <a class="link-btn"
                               @click="_cloneTask(record)">
                                <lang>克隆</lang>
                            </a>
                            <a class="link-btn"
                               style="border-left: 1px solid #D8D8D8;    padding-left: 9px;"
                               @click="_deleteTask(record)">
                                <lang>删除</lang>
                            </a>
                        </div>
                    </template>
                </sf-table>
                <div class="footer">
                    <sf-button size="normalless" @click="_deleteTaskSelect">
                        <lang>批量删除</lang>
                    </sf-button>
                </div>
            </sf-grid>
        </div>
    </div>
</template>

<script>
import {secToTime} from 'src/util/time'
import {SCHEDULE_MAP, TABS_MAP, HISTORY_STATUS_MAP} from "../const";


const PAGE_COUNT = 20;
const JOBS_LIST = {
    get: `/task-manage/api/v1/jobs/list`,
    delete: `/task-manage/api/v1/jobs`
};
export default {
    name: "HistoryTask",
    filters: {
        secToTime,
    },
    data() {
        return {
            searchParams: {
                search: '',
                pageSize: PAGE_COUNT,
                pageNum: 0,
                plat: 0,
                history: TABS_MAP['history_task'],
                orderBy: '',
                orderByMode: '',
                scheduleMode: '', // 执行方式
                startTime: '',
                endTime: '', // 结束时间
                jobStatus: '' // 运行状态
            },
            dateList: [],
            options_fix: {
                bufferView: false,
                selectionHide: false,
                
                // 配置这个后才可以实现保持勾选状态
                idProperty: 'id',
                pagination: {
                    activePage: 1,
                    pageSize: PAGE_COUNT,
                    pageSizes: [Number('10'), Number('20'), Number('50')]
                }
            }
        }
    },
    
    computed: {
        SCHEDULE_MAP() {
            return SCHEDULE_MAP;
        },
        
        scheduleModeOption() {
            return Object.keys(SCHEDULE_MAP).map(item => ({
                label: SCHEDULE_MAP[item],
                value: item
            }))
        },
        
        HISTORY_STATUS_MAP() {
            return HISTORY_STATUS_MAP;
        },
        
        jobStatusOption() {
            return Object.keys(HISTORY_STATUS_MAP).map(item => ({
                label: HISTORY_STATUS_MAP[item],
                value: item
            }))
        }
        
        
    },
    
    async mounted() {
        await this.getList(true);
        
    },
    methods: {
        async getList(flag = false) {
            this.$mask()
            let jsonData = await this.$ajax.post(JOBS_LIST.get, this.searchParams);
            this.$unmask();
            let table = this.$refs.table;
            let {success, data} = jsonData;
            if (!success) {
                return;
            }
            if (flag && (data.list.length === 0 || !table) ) { // 只有首次加载为空才需要这样
                return;
            }
            table.getPagination().setTotal(data.total);
            table.loadData(data.list || []);
            
        },
        
        _onPageChange(pageNum) {
            Object.assign(this.searchParams, {
                pageNum: pageNum - 1
            });
            this.getList();
        },
        
        _onSizeChange(nowPageIndex, nowPageSize) {
            Object.assign(this.searchParams, {
                pageNum: nowPageIndex - 1,
                pageSize: nowPageSize
            });
            this.getList();
        },
        
        onSort(columnVm, direction) {
            this.searchParams.orderBy = columnVm.dataIndex
            this.searchParams.orderByMode = direction.toLowerCase()
            this.getList();
        },
        
        _startSearch() {
            this.getList();
        },
        
        _reset() {
            this.searchParams = {
                ...this.searchParams,
                scheduleMode: '', // 执行方式
                startTime: '',
                endTime: '', // 结束时间
                jobStatus: '' // 运行状态
            }
            this.dateList = [];
            this.getList();
        },
        
        _datePickerChange(value) {
            if(!value) {
                this.searchParams.startTime = '';
                this.searchParams.endTime = '';
                return;
            }
            this.searchParams.startTime = value[0];
            this.searchParams.endTime = value[1];
        },
        
        _deleteTaskSelect() {
            this._deleteTask();
        },
        
        _cloneTask(record) {
            this.$store.commit('changeForm', {
                jobName: record.jobName,
                sqlText: record.sqlText,
                outputDataspace: record.outputDataspace,
                outputDataset: record.outputDataset,
                writeMode: record.writeMode,
                scheduleMod: record.scheduleMod,
                scheduleTim: record.scheduleTim
            })
            this.$store.commit('changeStep',0);
    
            this.$router.push({name: 'data_project'})
        },
        
        _deleteTask(record) {
            let item = record;
            let params = {};
            let title = '';
            if (item) {
                params.jobId = [item.jobId];
                title = _('确定要删除“{0}”任务吗？', item.jobName);
            } else {
                params.jobId = this.$refs.table?.getSelections().map(item => item.jobId)
                if (params.jobId.length === 0) {
                    this.$warn(_('未选择任务，删除失败！'), {autoHide: true})
                    return;
                }
                title = _('确定要删除这“{0}”个任务吗？', params.jobId.length);
            }
            this.$confirm({
                title: _('删除任务'),
                subTitle: title,
                msg: _('历史任务删除之后将无法恢复'),
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        this.ajaxDeleteTask(params);
                    }
                }
            });
        },
        
        async ajaxDeleteTask(params) {
            this.$mask();
            const jsonData = await this.$ajax.delete(`${JOBS_LIST.delete}`, params);
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('删除失败'));
            }
            this.$ok(_('删除成功'));
            this.getList();
        },
        
        copySuccess() {
            this.$ok('复制成功')
        },
        
        
        toDetail(record) {
            this.$router.push({
                name: 'task_detail_user',
                query: {
                    jobId: record.jobId,
                }
            })
        }
    }
}
</script>

<style scoped lang="less">
.history-task {
    height: calc(100% - 41px);
    
    .table-data {
        height: 100%;
        
        .sfv-grid {
            border: none;
            height: 100%;
            display: flex;
            flex-direction: column;
            position: relative;
    
            .sfv-toolbar {
                margin-bottom: 8px;
                height: 48px;
                
                /deep/ .sfv-toolbar_inner {
                    padding-top: 0 !important;
                    padding-left: 0 !important;
                }
                
                /deep/ .el-input__inner {
                    border-radius: 2px;
                }
                
            }
            
            .sfv-table {
                flex: 1;
                height: calc(100% - 56px);
    
                /deep/ .sfv-table_cell-center {
                    text-align: center !important;
                }
                
                /deep/ .sfv-table_cell-left {
                    text-align: left !important;
                }
                
                /deep/ .sfv-table_header-cell {
                    height: 42px;
                }
                
                /deep/ .sfv-table_header {
                    border: none;
                }
                
                /deep/ .sfv-pagination__wrapper {
                    bottom: 0;
                }
                
                /deep/ .page-size {
                    margin: -4px 8px;
                }
    
                /deep/  .sfv-table_body {
                    .sfv-scrollbar {
                        .sfv-scrollbar-body {
                            width: 100%;
                        }
                    }
                }
                
                //    视觉需求奇奇怪怪的样式覆盖
            }
        }
        
        .output {
            display: flex;
            align-content: center;
            justify-content: center;
            
            .output__text {
                flex: 1;
            }
            
            .iconfont {
                cursor: pointer;
            }
            
            .iconfont:hover {
                color: #1770E6
            }
        }
        
        .footer {
            position: absolute;
            bottom: 0;
            z-index: 19;
            display: flex;
            align-items: center;
        }
    }
}
</style>
